const mongoose = require('mongoose');
const dbUrl = require('./database');
const model = require("./model");
const User = model.User;
const Project = model.Project;

console.log("Test Start");

mongoose.connect(dbUrl, { useNewUrlParser:true }, function (err) {
  if (err) {
    console.error("\t Mongo Database connot connected!");
  }
});

function GetUserInfo (username, callback) {
  User.find({'username': username}).then(function (rst) {
    if (callback) callback(rst);
  });
}

// 项目更新
exports.ProjectUpdate = function (username, pId, dt, callback) {
  var target = {
    'name': dt.name, 
    'describe': dt.describe,
    'data': dt.data,
    'layout': dt.layout,
    'updateTime': Date.now(),
  };
  Project.update({'username': username, '_id': pId}, target, function (err, rst) {
    if (callback) callback(err, rst);
    if (!err) console.log(username + '更新了项目，' + rst);
  });
}

// 项目保存
exports.ProjectSave = function (username, dt, callback) {
  var project = new Project({
    'username': username, 'name': dt.name, 'describe': dt.describe, 
    'data': dt.data,
    'layout': dt.layout,
    'createTime':Date.now()
  });
  project.save(function (err, rst) {
    let id = err ? -1 : rst._id.toString()
    if (callback) callback(err, id);
    if (!err) console.log(username + '创建了项目' + id);
  });
}

// 项目列表
exports.ProjectList = function (username, callback) {
  Project.find({'username': username}, function (err, rst) {
    if (callback) callback(err, rst);
  });
}

// 项目数据
exports.ProjectInfo = function (projectId, callback) {
  Project.find({'_id': projectId}, function (err, rst) {
    if (callback) callback(err, rst);
  });
}

// 用户登录·登录日志
exports.UserLogin = function (username, password, callback) {
  User.find({'username': username, 'password':password}, function (err, rst) {
    if (callback) callback(err, rst);
    if (rst.length === 0) return;
    console.log('用户登录成功: ' + username);
    User.update({'username': username}, {'lastAccess':Date.now()}, () => {});
  });
}

// 用户注册或增加
exports.UserAdd = function (userInfo, callback) {
  var user = new User(userInfo);
  user.save(function (err, rst) {
    if (callback) callback(err, rst);
    if (!err) console.log('用户添加成功: ' + rst.username);
  });
}

this.UserAdd({ username: 'test', password: '123456', email: '5229472731@qq.com' }, (err, rst) => {
  console.log(err);
  console.log(rst);
});

// GetUserInfo('test1');
// this.UserLogin('test1', '123456', function (r) {
//   console.log(r);
// });

// this.Save('n123', '123456');
// this.Update('n123', '5b6d4fa48dcf1f41bc983d49', {'row':12});

// User.update({'username': 'test1'}, {'password':'1211121a'}, () => {});
